package favorite

import (
	"context"
	"strconv"
	"strings"

	"mall/common/globalkey"
	"mall/common/jwt"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/api/internal/svc"
	"mall/service/forum/api/internal/types"
	"mall/service/forum/api/internal/utils/parse"
	"mall/service/forum/rpc/forumclient"
	"mall/service/product/rpc/productclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetShopGoodsFavoriteLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetShopGoodsFavoriteLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetShopGoodsFavoriteLogic {
	return &GetShopGoodsFavoriteLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetShopGoodsFavoriteLogic) GetShopGoodsFavorite(
	req *types.GetShopGoodsFavoriteReq,
	headers *[]*types.Header,
) (resp *types.GoodsListResp, err error) {
	userId := jwt.GetUserId(l.ctx)
	if userId == 0 {
		return nil, resultx.NewErrCode(resultx.TOKEN_EXPIRE_ERROR)
	}

	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	favPreload := "forumUserCollect:Id,ObjectId"
	// 构造查询条件
	var favFilters []string
	favFilters = append(favFilters, "UserId,equalTo:"+strconv.FormatInt(int64(userId), 10))
	favFilters = append(favFilters, "PlatformId,equalTo:"+strconv.FormatInt(int64(globalkey.ThirdPartyPlatformWechatMini), 10))
	favFilters = append(favFilters, "ObjectType,equalTo:"+strconv.FormatInt(int64(globalkey.AttachmentLogTypeProduct), 10))
	favFilters = append(favFilters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))
	var platformId uint32 = globalkey.ThirdPartyPlatformWechatMini

	ret, err := l.svcCtx.ForumRpc.GetUserCollectList(l.ctx, &forumclient.BaseListReq{
		Offset:     uint32((page - 1) * pageSize),
		Limit:      uint32(pageSize),
		Preload:    pointy.GetPointer(favPreload),
		Filter:     pointy.GetPointer(strings.Join(favFilters, ";")),
		VisitorId:  pointy.GetPointer(userId),
		PlatformId: pointy.GetPointer(platformId),
	})
	if err != nil {
		return nil, err
	}

	var hasNextPage bool
	var hasPreviousPage bool
	if ret.HasNextPage != nil && *ret.HasNextPage > 0 {
		hasNextPage = true
	}
	if ret.HasPreviousPage != nil && *ret.HasPreviousPage > 0 {
		hasPreviousPage = true
	}

	resp = &types.GoodsListResp{
		BaseListInfo: types.BaseListInfo{
			HasNextPage:     hasNextPage,
			HasPreviousPage: hasPreviousPage,
		},
	}

	if len(ret.List) > 0 {
		var pids []string
		for _, v := range ret.List {
			if v.ObjectId != nil && *v.ObjectId > 0 {
				pids = append(pids, strconv.FormatInt(int64(*v.ObjectId), 10))
			}
		}

		preload := "product:Id,Title,Slug"
		eagerLoad := "product:productMeta,productMedia,productRelationship"
		preload += ";productMeta:mediaUrl,retailPriceMin,hotSell"
		preload += ";productMedia:Uid,Url,altText,metaData"
		preload += ";productRelationship:PerfumeId,PerfumeName,PerfumeSlug,BrandId,BrandName,BrandSlug"

		var filters []string
		filters = append(filters, "Id,in:"+strings.Join(pids, ","))
		if req.Type != nil && *req.Type != globalkey.ProductTypePhysical {
			filters = append(filters, "virtual,equalTo:"+strconv.FormatInt(int64(*req.Type), 10))
		} else {
			filters = append(filters, "virtual,equalTo:"+strconv.FormatInt(int64(globalkey.ProductTypePhysical), 10))
		}
		filters = append(filters, "Status,equalTo:"+strconv.FormatInt(int64(globalkey.StatusEnabled), 10))

		res, err := l.svcCtx.ProductRpc.GetProductList(l.ctx, &productclient.BaseListReq{
			Preload:    pointy.GetPointer(preload),
			EagerLoad:  pointy.GetPointer(eagerLoad),
			Filter:     pointy.GetPointer(strings.Join(filters, ";")),
			VisitorId:  pointy.GetPointer(userId),
			PlatformId: pointy.GetPointer(platformId),
		})
		if err != nil {
			return nil, err
		}

		if len(res.List) > 0 {
			idProductMap := make(map[uint64]*types.GoodsInfo)
			for _, v := range res.List {
				if v.Id == nil || *v.Id == 0 {
					continue
				}

				var retailPriceMin *string
				var isNew *bool
				var isHot *bool
				var mediaUrl *string
				if len(v.Meta) > 0 {
					for _, m := range v.Meta {
						if m.Key == nil || m.Value == nil {
							continue
						}

						val := *m.Value
						switch *m.Key {
						case "retailPriceMin":
							retailPriceMin = pointy.GetPointer(val)
						case "isNew":
							if val == "1" {
								isNew = pointy.GetPointer(true)
							}
						case "isHot":
							if val == "1" {
								isHot = pointy.GetPointer(true)
							}
						case "hotSell":
							if val == "1" {
								isHot = pointy.GetPointer(true)
							}
						case "mediaUrl":
							mediaUrl = pointy.GetPointer(val)
						}
					}
				}

				var brandTitle *string
				if len(v.Relations) > 0 {
					for _, m := range v.Relations {
						if m.Key != nil {
							switch *m.Key {
							case globalkey.ProductRelationNameBrand:
								brandTitle = m.Name
							}
						}
					}
				}

				if len(v.Media) > 0 {
					for _, m := range v.Media {
						if mediaUrl != nil {
							break
						}

						var url string
						if m.Url != nil && len(*m.Url) > 0 {
							url = *m.Url
						}
						if len(url) == 0 && m.Uri != nil && len(*m.Uri) > 0 {
							url = *m.Uri
						}
						mediaUrl = pointy.GetPointer(url)
					}
				}

				var preTag *string
				if isHot != nil && *isHot {
					preTag = pointy.GetPointer("热卖")
				} else if isNew != nil && *isNew {
					preTag = pointy.GetPointer("新品")
				}

				idProductMap[*v.Id] = &types.GoodsInfo{
					Id:       v.Id,
					PreTag:   preTag,
					Brand:    brandTitle,
					Title:    v.Title,
					Slug:     v.Slug,
					MinPrice: retailPriceMin,
					ImageUrl: mediaUrl,
				}
			}

			for _, v := range ret.List {
				if v.ObjectId != nil && *v.ObjectId > 0 {
					if goods, ok := idProductMap[*v.ObjectId]; ok {
						goods.Uid = v.Id
						resp.List = append(resp.List, goods)
					}
				}
			}
		}
	}

	*headers = []*types.Header{
		{
			Key:   "x-class",
			Value: "com.djx.appview.GoodsFavPage",
		},
	}

	return resp, nil
}
